package com.my.demo.config;

import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author liangyuanshao
 * @date 2021/12/10 - 11:04
 */
@Configuration
@EnableAsync
public class AsyncTaskConfig implements AsyncConfigurer {

  // ThredPoolTaskExcutor的处理流程
  // 当池子的线程数大于corePoolSize时，多余的线程会等待keepAliveTime长时间，如果无请求可处理就自行销毁

  @Override
  @Bean
  public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
    //设置核心线程数
    threadPool.setCorePoolSize(2);
    //设置最大线程数
    threadPool.setMaxPoolSize(10);
    //线程池所使用的缓冲队列
    threadPool.setQueueCapacity(10);
    //等待任务在关机时完成--表明等待所有线程执行完
    threadPool.setWaitForTasksToCompleteOnShutdown(true);
    // 等待时间 （默认为0，此时立即停止），并没等待xx秒后强制停止
    threadPool.setAwaitTerminationSeconds(60);
    //  线程名称前缀
    threadPool.setThreadNamePrefix("OCR-Async-");
    // 初始化线程
    threadPool.initialize();
    return threadPool;
  }

  @Override
  public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    return null;
  }
}
